package com.leisurexi.aop.overview;

import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;

/**
 * AOP 目标过滤示例（通过 Java 反射相关的 API）
 *
 * @author: leisurexi
 * @date: 2021-05-20 15:39
 */
public class TargetFilterDemo {

    public static void main(String[] args) throws ClassNotFoundException {
        String targetClassName = "com.leisurexi.aop.overview.EchoService";
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        Class<?> targetClass = classLoader.loadClass(targetClassName);
        Method targetMethod = ReflectionUtils.findMethod(targetClass, "echo", String.class);
        System.out.println(targetMethod);

        // 查找方法 throws 类型为 NullPointerException
        ReflectionUtils.doWithMethods(targetClass,
                method -> System.out.println("仅抛出 NullPointerException 异常的方法: " + method),
                method -> {
                    Class<?>[] exceptionTypes = method.getExceptionTypes();
                    return exceptionTypes.length == 1 && NullPointerException.class == exceptionTypes[0];
                });

    }

}
